package com.oto.web.resource;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.Constants;
import com.oto.LogType;
import com.oto.Result;
import com.oto.model.FlowDO;
import com.oto.model.LogDO;
import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2011-1-15
 */
@Path("/search")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class SearchResource extends BaseResource {

	@GET
	public Response search(@QueryParam(value = "key") String key) throws URISyntaxException {
		LogDO log = new LogDO(LogType.SEARCH, key); // log

		if (key == null || key.trim().equals("")) {
			return Response.seeOther(new URI("/")).build();
		}

		Collection<String> keys = searchService.parse(key);
		if (keys.isEmpty()) {
			log.setResult(Result.EMPTY_PARSE);
		}
		List<FlowDO> flows = searchService.search(FlowDO.class, keys, Constants.MED_SIZE);
		if (flows.isEmpty()) {
			log.setResult(Result.EMPTY_RESULT);
		} else {
			log.setResult(Result.DONE);
		}
		messageService.store(log);
		return Response.ok(new Viewable("index", flows)).build();
	}
}
